﻿//////////////////////////////////////////////////////////////////////////////
//
// Copyright © 1998-2024 Glodon Company Limited.
//
// Licensed under the MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the “Software”),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//////////////////////////////////////////////////////////////////////////////
#include "RectPickSuperInstanceBeforeSubInstanceEventHandler.h"

#include "IDocument.h"
#include "IPick.h"
#include "IPickResult.h"
#include "IPickEventArgs.h"
#include "IGraphicsNodeReference.h"
#include "IInstance.h"
#include "IElementModelShape.h"
#include "IGraphicsElementShape.h"
#include "EnableCompileWarning_The_LAST_IncludeInCpp.h"

using namespace gcmp;

namespace
{
    struct IntersectData 
    {
        IntersectData(const Vector3d& point, const IGraphicsNode* gNode, Matrix4d* matrix) : 
            untransformedIntersectPoint(point),
            intersectGNode(gNode),
            transform(matrix)
        {}

        const Vector3d untransformedIntersectPoint;
        const IGraphicsNode* intersectGNode;
        Matrix4d* transform;
    };
}

void RectPickSuperInstanceBeforeSubInstanceEventHandler::Process(IDocument* pDoc, IPickEventArgs * pArgs, const Vector3d & pos) const
{
    DBG_WARN_AND_RETURN_VOID_UNLESS(pDoc && pArgs, L"ParamInputted is invalid!",L"GDMPLab",L"2024-03-30");

    OwnerPtr<IPickResult> pickResult = IPickResult::Create();
    DBG_WARN_AND_RETURN_VOID_UNLESS(pickResult, L"pickResult is nullptr!",L"GDMPLab",L"2024-03-30");
    OwnerPtr<IPickResult> resultInput = pArgs->GetPickCandidates().Clone();
    DBG_WARN_AND_RETURN_VOID_UNLESS(resultInput, L"resultInput is nullptr!",L"GDMPLab",L"2024-03-30");

    std::vector<OwnerPtr<IPick>>& picksInputted = resultInput->GetAllPicks();
    if (picksInputted.size() == 0)
        return;

    DBG_WARN_AND_RETURN_VOID_UNLESS(1 == picksInputted.size(), L"1 != picksInputted.size()!",L"GDMPLab",L"2024-03-30");

    const std::vector<OwnerPtr<IGraphicsNodeReference>>& gNodeRefs = picksInputted[0]->GetAllGraphicsNodeReferences();
    
    // 用于存储拾取返回的所有ElementIds
    std::set<ElementId> allGNodeRefsIds;
    // 用于存储被拾取到的嵌套族实例树中的所有InstanceIds及拾取相交数据，每个pair对应一个子vector<ElementId>、拾取相交数据
    std::vector<std::pair<std::vector<ElementId>, IntersectData>> allNestedFamilyInstances;

    OwnerPtr<IPick> resultPick = IPick::Create();
    DBG_WARN_AND_RETURN_VOID_UNLESS(resultPick, L"创建拾取结果失败",L"GDMPLab",L"2024-03-30");
    for (const auto& opGNodeRef : gNodeRefs)
    {
        DBG_WARN_AND_CONTINUE_UNLESS(opGNodeRef, L"图形节点引用为空",L"GDMPLab",L"2024-03-30");
        const IElement* pElement = pDoc->GetElement(opGNodeRef->GetElementId());
        if (!pElement)
            continue;

        allGNodeRefsIds.insert(opGNodeRef->GetElementId());

        const IInstance* pInstance = quick_cast<IInstance>(pElement);
        if (!pInstance)
        {
            resultPick->AddGraphicsNodeReference(*opGNodeRef);
            continue;
        }

        // 嵌套族相关处理逻辑
        if (ElementId::InvalidID != pInstance->GetSuperInstanceId() || !pInstance->GetSubInstanceIds().empty())
        {
            ElementId currentId = pInstance->GetSuperInstanceId();
            std::vector<ElementId> superLineIds;
            superLineIds.emplace_back(opGNodeRef->GetElementId());
            while (ElementId::InvalidID != currentId)
            {
                superLineIds.emplace_back(currentId);

                pInstance = quick_cast<IInstance>(pDoc->GetElement(currentId));
                DBG_WARN_AND_BREAK_UNLESS(pInstance, L"pInstance is nullptr!",L"GDMPLab",L"2024-03-30");
                currentId = pInstance->GetSuperInstanceId();
            }

            OwnerPtr<GraphicsNodeAndTransform> intersectGraphicsNode = opGNodeRef->GetIntersectGraphicsNode();
            DBG_WARN_AND_CONTINUE_UNLESS(intersectGraphicsNode, L"intersectGraphicsNode is nullptr!",L"GDMPLab",L"2024-03-30");
            const Vector3d& untransformedIntersectPoint = opGNodeRef->GetUntransformedIntersectPoint();
            const IGraphicsNode* intersectGNode = (intersectGraphicsNode->m_wpGraphicsNode).Get();
            Matrix4d* transform = (intersectGraphicsNode->m_opTransfrom).get();

            std::vector<ElementId> allSubInstanceIds = pInstance->GetAllSubInstanceIds();
            allSubInstanceIds.emplace_back(superLineIds.back());

            if (pArgs->IsReversePick())
            {
                for (auto& id : allSubInstanceIds)
                {
                    OwnerPtr<IGraphicsNodeReference> nodeRef = IGraphicsNodeReference::CreateGraphicsElementShapeReference(id);
                    DBG_WARN_AND_BREAK_UNLESS(nodeRef, L"nodeRef is nullptr!",L"GDMPLab",L"2024-03-30");
                    nodeRef->SetIntersectData(untransformedIntersectPoint, intersectGNode, transform);
                    resultPick->AddGraphicsNodeReference(*nodeRef);
                }
                continue;
            }

            allNestedFamilyInstances.emplace_back
                (std::make_pair(allSubInstanceIds, IntersectData(untransformedIntersectPoint, intersectGNode, transform)));

            continue;
        }

        resultPick->AddGraphicsNodeReference(*opGNodeRef);
    }

    // 依据allGNodeRefsIds & allNestedFamilyInstances分析，正选状态下，是否拾取到整颗嵌套族实例树
    if (!pArgs->IsReversePick())
    {
        for (const auto& pairItem : allNestedFamilyInstances)
        {
            bool tag = true;
            for (const auto& id : pairItem.first)
            {
                if (allGNodeRefsIds.end() == allGNodeRefsIds.find(id))
                {
                    // 当前ElementId虽然不在resultInput中，但若child为空，则continue
                    const IInstance* pInstance = quick_cast<IInstance>(pDoc->GetElement(id));
                    CHAINED_CALL_AND_RETURN_VOID_UNLESS(const IGraphicsElementShape*, pGrep, pInstance, GetElementModelShape(), GetGraphicsElementShape());
                    DBG_WARN_AND_RETURN_VOID_UNLESS(pGrep, L"pGrep is nullptr!",L"GDMPLab",L"2024-03-30");
                    std::vector<const IGraphicsNode*> allChild = pGrep->GetAllChildren();
                    if (allChild.empty())
                        continue;

                    // 所有的child都不可见，则continue
                    bool isVisible = false;
                    for (auto pGNode : allChild)
                    {
                        if (pGNode->IsVisible())
                        {
                            isVisible = true;
                            break;
                        }
                    }
                    if (!isVisible)
                        continue;

                    // 否则当前ElementId未被正框选到
                    tag = false;
                    break;
                }
            }

            if (tag)
            {
                for (const auto& id : pairItem.first)
                {
                    OwnerPtr<IGraphicsNodeReference> nodeRef = IGraphicsNodeReference::CreateGraphicsElementShapeReference(id);
                    DBG_WARN_AND_BREAK_UNLESS(nodeRef, L"nodeRef is nullptr!",L"GDMPLab",L"2024-03-30");
                    nodeRef->SetIntersectData(pairItem.second.untransformedIntersectPoint, pairItem.second.intersectGNode, pairItem.second.transform);
                    resultPick->AddGraphicsNodeReference(*nodeRef);
                }
            }
        }
    }

    pickResult->AddPick(TransferOwnership(resultPick));
    pArgs->SetPickCandidates(*pickResult);
}
